<template>
  <div class="h-full flex flex-col p-4 overflow-hidden">
    <!-- 搜索和添加组织分类区域 -->
    <!-- <div class="bg-white p-4 mb-4 rounded shadow-sm">
      <div class="flex items-center justify-between">
        <div class="flex gap-2">
          <el-input
            v-model="searchParams.organizationName"
            placeholder="Organization Name"
            clearable
            :prefix-icon="Search"
          />
          <el-button type="primary" @click="handleSearch">Search</el-button>
        </div> -->
        <!-- 移除添加按钮，因为这个模块主要用于修改权限 -->
      <!-- </div>
    </div> -->

    <!-- 组织分类列表表格 -->
    <div
      class="bg-white p-4 rounded shadow-sm flex-1 flex flex-col overflow-hidden"
    >
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="tableData.length > 0"
        @retry="retryFetch"
      >
        <div class="flex-1 overflow-auto">
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            height="100%"
            class="adaptive-table design-table"
            table-layout="auto"
            :header-cell-style="headerCellStyle"
          >
          <!-- 数据列 - 完全自适应宽度 -->
          <el-table-column
            prop="organizationType"
            :label="t('authority.organization.organizationType')"
            min-width="150"
            class-name="data-column"
          >
            <template #default="scope">
              <span v-if="scope.row.organizationType === 0">Zendure</span>
              <span v-else-if="scope.row.organizationType === 1">{{ t('authority.role.installer') }}</span>
              <span v-else-if="scope.row.organizationType === 2">{{ t('authority.role.distributor') }}</span>
              <span v-else-if="scope.row.organizationType === 3">Organization Client</span>
              <span v-else>{{ scope.row.organizationType }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="authorityType"
            :label="t('authority.organization.applicationType')"
            min-width="150"
            class-name="data-column"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.authorityType === '0'" type="primary">Web</el-tag>
              <el-tag v-else-if="scope.row.authorityType === '1'" type="success">App</el-tag>
              <el-tag v-else-if="scope.row.authorityType === '0,1' || scope.row.authorityType === '1,0'" type="warning">Web+App</el-tag>
              <el-tag v-else type="info">-</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="updateDate"
            :label="t('authority.role.modifyTime')"
            min-width="180"
            class-name="data-column"
          />
          <el-table-column
            prop="modifyUser"
            :label="t('authority.role.modifyUser')"
            min-width="150"
            class-name="data-column"
          />
          
          <!-- 操作列 - 固定宽度，始终在右侧 -->
          <el-table-column
            :label="t('authority.common.operation')"
            width="120"
            fixed="right"
            align="center"
            class-name="operation-column"
          >
            <template #default="scope">
              <div class="operation-buttons">
          <el-button 
            link 
            type="primary" 
            v-if="hasPermission('sys:suborganization:rootupdate') || isSuperAdmin"
            @click="handleModify(scope.row)"
          >
                  {{ t('authority.organization.modifyOrganization') }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        </div>

        <!-- 分页 -->
        <div class="mt-4 flex justify-end">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50,100 ]"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </PageState>
    </div>

    <!-- 组织分类表单抽屉组件 -->
    <type-form-drawer
      v-model:visible="drawerVisible"
      :form-data="formData"
      :dialog-type="dialogType"
      @submit-success="handleDrawerSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
// 组织分类管理页（Organization Classification）
// 职责：
// - 展示四类固定组织（Zendure/安装商/经销商/组织类客户）
// - 支持查看并调整其 Web 权限（通过抽屉修改）
// - 权限变更后刷新菜单与权限缓存
import { ref, reactive, onMounted, defineAsyncComponent } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  getOrganizationTypeList
} from "./data";
import { useI18n } from "@/composables/useI18n";
import { usePermission } from "@/composables/usePermission";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";

const TypeFormDrawer = defineAsyncComponent(() => import("./components/TypeFormDrawer.vue"));

// 多语言
const { t } = useI18n();
// 权限
const { hasPermission, isSuperAdmin } = usePermission();

// 搜索参数
const searchParams = reactive({
  organizationName: ""
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const errorMessage = ref("");

// 表头样式：与设计稿一致的浅灰背景
const headerCellStyle = () => ({
  background: '#F5F6FA',
  color: '#111827',
  fontWeight: 600
});

// 抽屉控制
const drawerVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formData = ref({});

// 初始化
onMounted(() => {
  loadTableData();
});

// 加载表格数据
const loadTableData = async () => {
  loading.value = true;
  try {
    const { list, totalCount } = await getOrganizationTypeList({
      page: currentPage.value,
      pageSize: pageSize.value,
      organizationName: searchParams.organizationName
    });

    const normalizeAuthorityType = (input: any): string => {
      if (input == null) return '';
      let arr: string[] = [];
      if (Array.isArray(input)) arr = input.map((x: any) => String(x));
      else if (typeof input === 'string') arr = input.split(',').map(s => s.trim());
      else arr = [String(input)];
      // 兼容已是文本的情况
      arr = arr.map(v => (v === 'Web' ? '0' : v === 'App' ? '1' : v));
      const set = Array.from(new Set(arr)).sort();
      if (set.length === 0) return '';
      if (set.length === 1) return set[0];
      return set.join(',');
    };

    tableData.value = list.map((item: any) => ({
      ...item,
      organizationType: item.organizationType ?? 0,
      authorityType: normalizeAuthorityType(item.authorityType),
      updateDate: item.updateDate || item.modifyTime || item.createDate || '-',
      modifyUser: item.modifyUser || '-'
    }));
    total.value = totalCount;
  } catch (error) {
    console.error('加载组织分类数据失败:', error);
    ElMessage.error(t('messages.loadDataFailed'));
  } finally {
    loading.value = false;
  }
};

// 搜索：重置到第 1 页并重新加载
const handleSearch = () => {
  currentPage.value = 1;
  loadTableData();
};

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  handleSearch();
}, 500, { leading: false, trailing: true });

// 分页：修改每页条数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadTableData();
};

// 分页：跳转页码
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadTableData();
};

// 修改组织分类：打开抽屉并回填数据
const handleModify = async (row: any) => {
  dialogType.value = "edit";
  formData.value = { ...row };
  drawerVisible.value = true;
};

// 抽屉提交成功回调：根据返回结果提示与刷新
const handleDrawerSuccess = async (data: any) => {
  try {
    console.log('[OrgType] 提交返回:', data);
    
    // 这里主要是权限修改，不需要区分添加和更新
    if (data.success) {
      ElMessage.success(data.message || t('messages.updateSuccess'));
      // 刷新菜单和权限，观察分配后的展示
      const { useAppStore } = await import('@/store');
      await useAppStore().initApp();
    } else {
      ElMessage.error(data.message || t('messages.updateFailed'));
    }

    drawerVisible.value = false;
    loadTableData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(t('messages.operationFailed'));
  }
};

// 重试加载
const retryFetch = () => {
  errorMessage.value = "";
  loadTableData();
};
</script>

<style lang="scss" scoped>
/* 表格样式*/
.adaptive-table {
  // 设置表格布局为自动，实现完全自适应
  :deep(.el-table) {
    table-layout: auto;
    --el-table-border-color: #E5E7EB; // 全局分隔线颜色
  }
  
  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  // 表头：统一浅灰背景，深色文字，加粗，圆角
  :deep(.el-table__header-wrapper),
  :deep(.el-table__header-wrapper th),
  :deep(.el-table__header-wrapper tr),
  :deep(.el-table__header-wrapper .cell),
  :deep(.el-table__header-wrapper thead),
  :deep(.el-table__header-wrapper thead tr),
  :deep(.el-table__header-wrapper thead tr th) {
    background-color: #F5F6FA !important;
    color: #111827 !important;
    font-weight: 600;
    border-bottom: 1px solid #E5E7EB !important;
    padding: 10px 16px;
  }
  
  // 表头左右圆角
  :deep(.el-table__header-wrapper thead tr th:first-child) {
    border-top-left-radius: 8px;
  }
  :deep(.el-table__header-wrapper thead tr th:last-child) {
    border-top-right-radius: 8px;
  }
  
  // 顶部细线颜色
  :deep(.el-table__inner-wrapper::before) {
    background-color: #E5E7EB !important;
    height: 1px;
  }

  // 表体：白底，文字颜色，底部分隔线，内边距
  :deep(.el-table__body tr),
  :deep(.el-table__body td) {
    background-color: #ffffff !important;
  }
  
  :deep(.el-table__body .el-table__cell) {
    color: #374151;
    padding: 12px 16px;
    border-bottom: 1px solid #E5E7EB !important;
  }
  
  // 行 hover 效果
  :deep(.el-table__body tr:hover > td) {
    background: #F9FAFB !important;
  }
  
  // 数据列完全自适应宽度
  :deep(.data-column) {
    .cell {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: keep-all;
    }
  }
  
  // 操作列固定样式，确保始终在右侧
  :deep(.operation-column) {
    position: sticky;
    right: 0;
    z-index: 2;
    background-color: var(--el-table-bg-color);
    
    .cell {
      white-space: nowrap;
      overflow: hidden;
    }
  }
  
  // 操作按钮容器 - 链接风格
  .operation-buttons {
    display: flex;
    gap: 0;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      flex-shrink: 0;
      min-width: auto;
      padding: 0 0; // 看起来像纯文本链接
      font-size: 13px;
      color: #0F766E; // 链接主色
    }
    
    .el-button:hover {
      color: #115E59;
      text-decoration: underline;
      background: transparent;
    }
    
    // 分隔竖线
    .el-button:not(:last-child)::after {
      content: "|";
      display: inline-block;
      margin: 0 10px;
      color: #6B7280; // 更深的灰色，更容易看见
    }
  }
  
  // 确保固定列在斑马纹表格中也有正确的背景色
  :deep(.el-table__row:nth-child(even)) {
    .operation-column {
      background-color: var(--el-table-row-hover-bg-color);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .adaptive-table {
    :deep(.el-table__body-wrapper) {
      overflow-x: auto;
    }
    
    .operation-buttons {
      flex-direction: column;
      gap: 4px;
      
      .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>
